<?php

use think\migration\Migrator;
use think\migration\db\Column;

class OptimizePartyTables extends Migrator
{
    public function up()
    {
        // 优化party表，增强当事人来源信息
        $table = $this->table('party');
        $table->addColumn('party_source', 'boolean', [
            'default' => 1,
            'comment' => '当事人来源：1-客户本身，2-客户联系人，3-外部人员'
        ])
        ->addColumn('contract_id', 'integer', [
            'limit' => 11,
            'default' => 0,
            'comment' => '关联合同ID'
        ])
        ->addColumn('contact_id', 'integer', [
            'limit' => 11,
            'default' => 0,
            'comment' => '关联客户联系人ID'
        ])
        ->addIndex(['party_source'])
        ->addIndex(['contract_id'])
        ->addIndex(['contact_id'])
        ->save();

        // 优化lawcase_party表，确保字段完整
        $table = $this->table('lawcase_party');
        // 检查relationship字段是否存在，如果不存在则添加
        if (!$table->hasColumn('relationship')) {
            $table->addColumn('relationship', 'boolean', [
                'default' => 0,
                'comment' => '法律关系：0-未知,1-原告,2-被告,3-第三人,4-上诉人,5-被上诉人,6-再审申请人,7-再审被申请人,8-申请执行人,9-被申请执行人'
            ])->save();
        }
    }

    public function down()
    {
        // 回滚party表的更改
        $table = $this->table('party');
        if ($table->hasColumn('party_source')) {
            $table->removeColumn('party_source');
        }
        if ($table->hasColumn('contract_id')) {
            $table->removeColumn('contract_id');
        }
        if ($table->hasColumn('contact_id')) {
            $table->removeColumn('contact_id');
        }
        $table->save();

        // 注意：不回滚oa_lawcase_party表的relationship字段，因为它可能是系统原有字段
    }
}